<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="4">
              <a-form-item label="部门" prop="type">
                <a-tree-select
                  v-model="queryParam.deptId"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="deptOptions"
                  placeholder="请选择"
                  :replaceFields="{
                    children: 'children',
                    title: 'menuName',
                    key: 'id',
                    value: 'id',
                  }"
                  @change="onMenuTreeChange"
                  allow-clear
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="客户经理">
                <a-select
                  placeholder="请选择客户经理"
                  v-model="queryParam.userId"
                  :getPopupContainer="
                    (triggerNode) => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="d in userNamesList"
                    :key="d.name"
                    :value="d.id"
                    >{{ d.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="服务机构">
                <a-select
                  placeholder="请选择服务机构"
                  v-model="queryParam.orgType"
                  :getPopupContainer="
                    (triggerNode) => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  style="width: 100%"
                  allow-clear
                  @change="handleGetProductInfo"
                >
                  <a-select-option
                    v-for="(d, index) in orgTypeOptions"
                    :key="index"
                    :value="d.dictValue"
                    >{{ d.dictLabel }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="产品名称">
                <a-select
                  placeholder="请选择产品"
                  v-model="queryParam.productId"
                  :getPopupContainer="
                    (triggerNode) => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="d in productList"
                    :key="d.productName"
                    :value="d.id"
                    >{{ d.productName }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="放款时间">
                <a-range-picker
                  v-model="queryParam.dateRange"
                  valueFormat="YYYY-MM-DD"
                  :show-today="true"
                />
              </a-form-item>
            </a-col>

            <a-col>
              <span
                class="table-page-search-submitButtons"
                style="float: right"
              >
                <a-button type="primary" @click="handleQuery"
                  ><a-icon type="search" />查询</a-button
                >
                <a-button style="margin-left: 8px" @click="resetQuery"
                  ><a-icon type="redo" />重置</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" style="overflow-y: auto; padding-top: 15px">
      <!-- 增加 -->

      <span
        style="
          position: absolute;
          top: 0;
          left: 0;
          z-index: 1;
          background: white;
          padding: 0 12px;
          margin-top: 10px;
          margin-left: 10px;
          font-weight: bold;
        "
      >
        默认当月
      </span>
      <a-table
        rowKey="id"
        :columns="sumcolumns"
        :data-source="sumOrgTypeStatisticList"
        size="middle"
        bordered
        :pagination="false"
        style="margin-top: 20px"
      >
        <span slot="amount" slot-scope="text">
          ¥ {{ formatNumber(text) }}
        </span>
        <span slot="counts" slot-scope="text">
          <a
            @click="handleShowRecord(queryParam.orgType)"
            v-if="text"
            style="font-weight: bold"
          >
            {{ text }}
          </a>
        </span>
      </a-table>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <advance-table
        :loading="loading"
        rowKey="id"
        :columns="columns"
        :expandedRowKeys="expandedKeys"
        @expand="onExpandCurrent"
        :data-source="bizCapBillList"
        title="还款信息"
        size="middle"
        tableKey="biz-loanBill-index-table"
        @refresh="getList"
        :format-conditions="true"
        :pagination="{
          current: queryParam.pageNum,
          pageSize: queryParam.pageSize,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: changeSize,
          onShowSizeChange: onShowSizeChange,
        }"
        :scroll="{ x: '100vh' }"
      >
        <span slot="expandedRowRender" slot-scope="{ record }">
          <detail-index
            ref="detailIndex"
            @getlist="resetQuery"
            :title="'[' + record.orgName + ']费用明细'"
            :parentQueryParam="queryParam"
            :orgType="record.orgType"
          />
        </span>
        <span slot="counts" slot-scope="{ text, record }">
          <a
            @click="handleShowRecord(record.orgType)"
            v-if="text"
            style="font-weight: bold"
          >
            {{ text }}
          </a>
        </span>
        <span slot="loanType" slot-scope="{ record }">
          {{ loanTypeFormat(record) }}
        </span>

        <span slot="isOverdue" slot-scope="{ text, record }">
          <template v-if="record.isOverdue == '1'">
            <a-badge status="error" />已逾期
          </template>
          <template v-else> <a-badge status="processing" />未逾期 </template>
        </span>

        <span slot="isPayAll" slot-scope="{ record }">
          <template v-if="record.isPayAll == '1'">
            <a-badge status="success" />已结清
          </template>
          <template v-else> <a-badge status="processing" />未结清 </template>
        </span>

        <span slot="operation" slot-scope="{ text, record }">
          <a
            @click="handleUpdate(record)"
            v-hasPermi="['biz:bizLoanBill:edit']"
          >
            修改
          </a>
        </span>
        <span slot="rowindex" slot-scope="{ index }">
          {{ index + 1 }}
        </span>
        <span slot="amount" slot-scope="{ text }">
          ¥ {{ formatNumber(text) }}
        </span>
      </advance-table>
    </a-card>

    <a-modal
      :visible="showRecordModal"
      title="资方放款明细"
      v-if="showRecordModal"
      @cancel="showRecordModal = false"
      @ok="showRecordModal = false"
      width="1200px"
      :dialog-style="{ top: '20px', heigth: '600px' }"
    >
      <capbill-record
        v-if="showRecordModal"
        ref="capbillRecord"
        :orgType="orgType"
        :parentQueryParam="queryParam"
        @ok="getList"
        @close="showRecordModal = false"
      />
    </a-modal>
  </div>
</template>
<script>
import { listBizProductInfo } from "@/api/biz/bizProductInfo";
import { orgTypeStatistic, sumOrgTypeStatistic } from "@/api/biz/bizCapBill";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import DetailIndex from "./detailIndex";
import { listUser } from "@/api/system/user";
import { listDeptTree } from "@/api/system/dept";

import capbillRecord from "@/views/biz/statistics/capbillRecord";
export default {
  name: "BizLoanBill",
  components: {
    AdvanceTable,
    DetailIndex,
    capbillRecord,
  },
  data() {
    return {
      orgType: "",
      showRecordModal: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 资方结算表格数据
      bizCapBillList: [],
      // 资方合计
      sumOrgTypeStatisticList: [],
      orgTypeOptions: [],
      // 结算类型字典
      typeOptions: [],
      // 结算状态字典
      statusOptions: [],

      productList: [],
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        userId: undefined,
        orgType: undefined,
        productId: undefined,
        dateRange: [],
      },
      columns: [
        {
          title: "机构",
          dataIndex: "orgName",
          align: "center",
          width: "210px",
        },
        // {
        //   title: "产品名称",
        //   dataIndex: "productName",
        //   ellipsis: true,
        //   align: "left",
        //   width: "230px",
        //   scopedSlots: { customRender: "jinjianId" },
        // },
        {
          title: "放款笔数",
          dataIndex: "counts",
          ellipsis: true,
          align: "center",
          width: "80px",
          scopedSlots: { customRender: "counts" },
        },
        {
          title: "放款金额(元)",
          dataIndex: "fkAmount",
          scopedSlots: { customRender: "amount" },
          align: "right",
          width: "180px",
        },

        {
          title: "收入金额(元)",
          dataIndex: "serviceAmountCheck",
          ellipsis: true,
          align: "right",
          width: "180px",
          scopedSlots: { customRender: "amount" },
        },
        {
          title: "资方结算金额(元)",
          dataIndex: "zifangAmount",
          align: "right",
          width: "180px",
          scopedSlots: { customRender: "amount" },
        },
      ],
      sumcolumns: [
        {
          title: "",
          ellipsis: true,
          dataIndex: "heji",
          align: "center",
          width: "50px",
        },
        {
          title: "机构数量",
          dataIndex: "orgNums",
          align: "center",
          width: "150px",
        },
        {
          title: "放款笔数",
          dataIndex: "counts",
          ellipsis: true,
          align: "center",
          width: "80px",
          scopedSlots: { customRender: "counts" },
        },
        {
          title: "放款金额(元)",
          dataIndex: "fkAmount",
          scopedSlots: { customRender: "amount" },
          align: "right",
          width: "180px",
        },

        {
          title: "收入金额(元)",
          dataIndex: "serviceAmountCheck",
          ellipsis: true,
          align: "right",
          width: "180px",
          scopedSlots: { customRender: "amount" },
        },
        {
          title: "资方结算金额(元)",
          dataIndex: "zifangAmount",
          align: "right",
          width: "180px",
          scopedSlots: { customRender: "amount" },
        },
      ],
      // 根据岗位删选员工
      postIds: ["gwzg", "rzgw", "qyjl", "sg"],
      // 部门信息
      deptOptions: [],
      userNamesList: [],
      isKefu: 2,
      expandedKeys: [],
    };
  },
  created() {
    this.getList();
    this.getDicts("zifang_jiesuan_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("zifang_jiesuan_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("org_type_options").then((response) => {
      this.orgTypeOptions = response.data;
    });
    this.getDeptList();
  },
  methods: {
    handleShowRecord(orgType) {
      this.showRecordModal = true;
      this.orgType = orgType;
    },
    handleGetProductInfo(value) {
      listBizProductInfo({ orgType: value, pageSize: 50 }).then((res) => {
        this.productList = res.data.list;
      });
    },
    onMenuTreeChange(value) {
      this.getUserList(value);
    },
    getUserList(deptId) {
      const params = {
        pageNum: 1,
        pageSize: 100,
        deptId: deptId,
      };
      if (this.isKefu) {
        params.isKefu = this.isKefu;
      }
      if (this.postIds) {
        params.postIds = this.postIds;
      }
      listUser(params).then((res) => {
        this.userNamesList = res.data.list;
      });
    },
    getDeptList() {
      listDeptTree("", 3).then((response) => {
        // this.expandTree(response.data, 3, this.expandedRowKeys);
        this.deptOptions = response.data;
      });
    },
    formatNumber(num) {
      return parseFloat(num || 0).toFixed(2);
    },
    onExpandCurrent(expandedKeys, row) {
      if (expandedKeys) {
        this.expandedKeys = [row.id];
      } else {
        this.expandedKeys = [];
      }
    },
    getList() {
      this.loading = true;
      orgTypeStatistic(
        this.addDateRange(this.queryParam, this.queryParam.dateRange)
      ).then((response) => {
        this.bizCapBillList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
      sumOrgTypeStatistic(
        this.addDateRange(this.queryParam, this.queryParam.dateRange)
      ).then((response) => {
        this.sumOrgTypeStatisticList = [];
        var data = response.data;
        data.heji = "合计：";
        this.sumOrgTypeStatisticList.push(data);
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
      };
      this.handleQuery();
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = size;
      this.getList();
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
  },
};
</script>
